package com.jm.controller;

import com.jm.common.util.Utils;
import com.jm.common.util.entity.R;
import com.jm.pojo.ShoppingCart;
import com.jm.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @GetMapping("/list")
    public R<List<ShoppingCart>> getShoppingCartList() {
        List<ShoppingCart> list = shoppingCartService.list();
        return R.success(list);
    }

    @PostMapping("/add")
    public R<ShoppingCart> addShoppingCart(@RequestBody ShoppingCart shoppingCart) {
        Long userId = Utils.getCurrentId();
        ShoppingCart result = shoppingCartService.getShoppingCart(shoppingCart, userId);
        if (result == null) {
//            表示购物车中没有这个玩具 将传入的对象设置一下用户Id保存即可
            shoppingCart.setUserId(userId);
            shoppingCart.setNumber(1);
            boolean save = shoppingCartService.save(shoppingCart);
            if (save) return R.success(shoppingCart);
            return R.error("数据保存至数据库失败");
        }
//        表示有玩具 修改数量+1即可
        result.setNumber(result.getNumber() + 1);
        boolean updateResult = shoppingCartService.updateById(result);
        if (updateResult) return R.success(result);
        return R.error("修改数量失败");
    }

    @PostMapping("/sub")
    public R<ShoppingCart> subShoppingCart(@RequestBody ShoppingCart shoppingCart) {
        Long userId = Utils.getCurrentId();
        ShoppingCart result = shoppingCartService.getShoppingCart(shoppingCart, userId);
        if (result == null) {
//            表示该条数据没有查找到
            return R.error("减少失败,该项目已不存在于数据库之中");
        }
//        表示有玩具 修改数量-1即可
        Integer number = result.getNumber();
        result.setNumber(number - 1);
        if (result.getNumber() == 0) {
//            减少完之后的数量若是等于一,则直接删除数据
            boolean removeResult = shoppingCartService.removeById(result.getId());
            if (removeResult) return R.success(result);
            return R.error("修改数量失败");
        }
        boolean updateResult = shoppingCartService.updateById(result);
        if (updateResult) return R.success(result);
        return R.error("修改数量失败");
    }

    @DeleteMapping("/clean")
    public R<String> cleanShoppingCart() {
        Long userId = Utils.getCurrentId();
        boolean b = shoppingCartService.cleanShoppingCartByUserId(userId);
        if (b) return R.success("清空购物车成功");
        return R.error("清空购物车失败");
    }
}
